package io.itit.ecp.admin.provide.action.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import icu.mhb.mybatisplus.plugln.extend.Joins;
import io.itit.ecp.admin.common.enums.CarbonPriceDataSourceTypeEnums;
import io.itit.ecp.admin.provide.action.req.CarbonPriceDataQueryReq;
import io.itit.ecp.admin.provide.action.req.CarbonPriceDataReq;
import io.itit.ecp.admin.provide.action.resp.CarbonPriceDataResp;
import io.itit.ecp.admin.provide.action.resp.CarbonPriceResp;
import io.itit.ecp.admin.server.entity.CarbonPriceDataEntity;
import io.itit.ecp.admin.server.entity.CarbonPriceEntity;
import io.itit.ecp.admin.server.entity.SceneProjectEntity;
import io.itit.ecp.admin.server.service.ICarbonPriceDataService;
import io.itit.grass.common.provide.action.req.BaseBatchIdReq;
import io.itit.grass.common.provide.action.req.BaseIdReq;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.provide.action.validation.IAdd;
import io.itit.grass.common.provide.action.validation.IQueryPage;
import io.itit.grass.common.provide.action.validation.IRequired;
import io.itit.grass.common.provide.action.validation.IUpdate;
import io.itit.grass.web.wall.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * 碳价数据管理
 */
@Api(tags = "碳价数据管理")
@RestController
@RequestMapping("/ecp-admin/carbonPriceData")
public class CarbonPriceDataController {

    @Resource
    private ICarbonPriceDataService carbonPriceDataService;

    @ApiOperation("分页查询")
    @PostMapping("queryPage")
    @RequiresPermissions("ecp-admin:carbonPriceData:search")
    public ResultResp<IPage<CarbonPriceDataResp>> queryPage(@RequestBody @Validated(IQueryPage.class) CarbonPriceDataQueryReq req) {
        Page<CarbonPriceDataResp> page = buildQW(req).joinPage(PageUtils.getPage(req, CarbonPriceDataResp.class), CarbonPriceDataResp.class);
        return ResultResp.success(page);
    }


    @ApiOperation("新增")
    @PostMapping("add")
    @RequiresPermissions("ecp-admin:carbonPriceData:add")
    public ResultResp<Boolean> add(@RequestBody @Validated({IAdd.class}) CarbonPriceDataReq req) {
        LocalDateTime start = LocalDateTime.parse(req.getDataTimeStart(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime end = LocalDateTime.parse(req.getDataTimeEnd(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        List<CarbonPriceDataEntity> entities = new ArrayList<>();
        String batchId = UUID.randomUUID().toString().replace("-", "");
        LocalDate temp = start.toLocalDate();
        LocalDate endDate = end.toLocalDate();
        do {
            CarbonPriceDataEntity dataEntity = new CarbonPriceDataEntity();
            dataEntity.setBatchId(batchId);
            dataEntity.setSceneProjectId(req.getSceneProjectId());
            dataEntity.setCcerPrice(req.getCcerPrice());
            dataEntity.setCarbonQuotaPrice(req.getCarbonQuotaPrice());
            dataEntity.setDataSourceType(CarbonPriceDataSourceTypeEnums.AUTO.getValue());
            dataEntity.setDataTime(temp.atTime(start.toLocalTime()));
            temp = temp.plusDays(1);
            entities.add(dataEntity);
        } while (temp.isBefore(endDate) || temp.isEqual(end.toLocalDate()));
        boolean res = carbonPriceDataService.saveBatch(entities);
        return ResultResp.success(res);
    }

    @ApiOperation("编辑")
    @PostMapping("update")
    @RequiresPermissions("ecp-admin:carbonPriceData:update")
    public ResultResp<Boolean> update(@RequestBody @Validated({IUpdate.class}) CarbonPriceDataReq req) {
        CarbonPriceDataEntity dataEntity = carbonPriceDataService.getById(req.getId());
        if (Objects.isNull(dataEntity)) {
            return ResultResp.fail("更新数据不存在");
        }
        dataEntity.setSceneProjectId(req.getSceneProjectId());
        dataEntity.setCcerPrice(req.getCcerPrice());
        dataEntity.setCarbonQuotaPrice(req.getCarbonQuotaPrice());
        dataEntity.setDataTime(LocalDateTime.parse(req.getDataTimeStart(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return ResultResp.success(carbonPriceDataService.updateById(dataEntity));
    }

    @ApiOperation("删除(根据Id删)")
    @PostMapping("deleteById")
    @RequiresPermissions("ecp-admin:carbonPriceData:deleteById")
    public ResultResp<Boolean> deleteById(@RequestBody @Validated({IRequired.class}) BaseIdReq req) {
        return ResultResp.success(carbonPriceDataService.removeById(req.getId()));
    }

    @ApiOperation("批量删除")
    @PostMapping("batchDelete")
    @RequiresPermissions("ecp-admin:carbonPriceData:batchDelete")
    public ResultResp<Boolean> batchDelete(@RequestBody @Validated({IRequired.class}) BaseBatchIdReq req) {
        return ResultResp.success(carbonPriceDataService.removeBatchByIds(req.getIds(), 1000));
    }

    private static JoinLambdaWrapper<CarbonPriceDataEntity> buildQW(CarbonPriceDataQueryReq req) {
        return Joins.of(CarbonPriceDataEntity.class)
                .leftJoin(SceneProjectEntity.class, SceneProjectEntity::getId, CarbonPriceDataEntity::getSceneProjectId)
                .selectAs(SceneProjectEntity::getProjectName, CarbonPriceResp::getProjectName)
                .end()
                .leftJoin(CarbonPriceEntity.class, CarbonPriceEntity::getSceneProjectId, CarbonPriceDataEntity::getSceneProjectId)
                .selectAs(CarbonPriceEntity::getCarbonExchangeId, CarbonPriceDataResp::getCarbonExchangeId)
                .end()
                .eq(StringUtils.hasLength(req.getSceneProjectId()), CarbonPriceDataEntity::getSceneProjectId, req.getSceneProjectId())
                .ge(StringUtils.hasLength(req.getStartTime()), CarbonPriceDataEntity::getDataTime, req.getStartTime())
                .le(StringUtils.hasLength(req.getEndTime()), CarbonPriceDataEntity::getDataTime, req.getEndTime())
                .orderByDesc(CarbonPriceDataEntity::getCreateTm);
    }

}
